# -*- encoding:utf8 -*-
import logging
import sys
sys.path.append('../')
from redis import StrictRedis
from ast import literal_eval
import redis
import os

proxies_file = os.path.join(os.path.dirname(__file__), 'proxies_400.txt')

class Proxies(object):
    def __init__(self, proxies_file_path, default_grade=0, stander_grade=0):
        self.default_grade = default_grade
        self.stander_grade = stander_grade
        self.sub_grade = 1
        self.proxies_file_path = proxies_file_path
        self.redi = redis.StrictRedis(host=redis_proxies['host'], port=redis_proxies['port'],password=redis_proxies['password'], db=8)

    #获取左边第一个
    def get_lpro(self,key):
        return literal_eval(self.redi.lindex(key,0))


    # 根据key来获取proxy,key不存在就初始化key
    def get_next_item(self, key):
        proxy_with_grade = self.redi.lpop(key)
        proxy, grade = literal_eval(proxy_with_grade)
        self.redi.rpush(key, (proxy, grade))
        return proxy, grade

    #获取代理
    def get_proxy(self, key):
        if self.redi.exists(key):
            proxy, grade = self.get_next_item(key)
        else:
            self.init_proxies(key=key)
            proxy, grade = self.get_next_item(key)
        while grade < self.stander_grade:
            proxy, grade = self.get_next_item(key)
        return proxy

    # 初始化一个key
    def init_proxies(self, key='default'):
        try:
            with open(proxies_file) as fr:
                proxies = fr.read().splitlines()
                proxies_with_grade = map(lambda x: ('http://{}'.format(x), self.default_grade), proxies)
            # 清除老的proxies
            self.redi.delete(key)
            self.redi.rpush(key, *proxies_with_grade)
            logging.info('init proxies for key:{0}'.format(key))
        except Exception as e:
            logger.error('init key {0} proxies fail reason is {1}'.format(key, e.message))
        return True


    # def sub_grade_with_proxy(self, key, aim_proxy):
    #     if key not in self.redi.keys():
    #         return 'key not exit'
    #     index = self.r_find_index(key, aim_proxy)
    #     if index is not None:
    #         self.sub_item_grade(key, index)
    #         return 'OK'
    #     return 'proxy not exit'
    #
    # def reset_all_grade(self, key):
    #     if key not in self.redis_connect.keys():
    #         return "key not exit"
    #     # tuple数组的redis存储问题
    #     all_proxies = map(literal_eval, self.redis_connect.lrange(key, 0, -1))
    #     new_proxies = map(lambda x: (x[0], self.default_grade), all_proxies)
    #     self.redis_connect.delete(key)
    #     self.redis_connect.rpush(key, *new_proxies)
    #     return 'OK'
    #
    #
    #
    # def get_item(self, index, key):
    #     proxy_with_grade = self.redis_connect.lindex(key, index)
    #     proxy, grade = literal_eval(proxy_with_grade)
    #     return proxy, grade
    #
    # def sub_item_grade(self, key, index):
    #     proxy, old_grade = self.get_item(index, key)
    #     new_grade = old_grade - self.sub_grade
    #     self.redis_connect.lset(key, index, (proxy, new_grade))
    #
    # # value -> index
    # def r_find_index(self, key, aim_proxy):
    #     start_index = -1
    #     proxies_len = self.redis_connect.llen(key)
    #     for i in range(proxies_len):
    #         index = start_index - i
    #         proxy, grade = self.get_item(index, key)
    #         if proxy == aim_proxy:
    #             return index
    #     return None


